package cn.csq.rpc.transport;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author csq
 * @version 1.0.0
 * @ClassName HTTPTransportServer.java
 * @Description 网络传输server实现
 * @createTime 2021年12月19日 23:55:00
 */
@Slf4j
public class HTTPTransportServer implements TransportServer{

    private RequestHandler handler;

    /**
     * server基于jetty
     */
    private Server server;

    @Override
    public void init(int port, RequestHandler handler) {
        this.handler = handler;
        this.server = new Server(port);

        //servlet 接收请求
        ServletContextHandler ctx = new ServletContextHandler();
        server.setHandler(ctx);
        //创建一个 处理网络请求的抽象 ServletHolder
        ServletHolder holder = new ServletHolder(new RequestServlet());
        //处理所有路径
        ctx.addServlet(holder, "/*");
    }

    @Override
    public void start() {
        //jetty server start
        try {
            server.start();
            //这个方法会立马方法 我们为了避免立马返回
            // 用开启一个线程进行 等待server进行关闭
            server.join();
        } catch (Exception e) {
            log.error("server star出现异常，" + e.getMessage(), e);
        }


    }

    @Override
    public void close() {
        try {
            server.stop();
        } catch (Exception e) {
            log.error("server close出现异常，"+e.getMessage(),e);
        }
    }

    @Override
    public void stop() {

    }

    /**
     * 创建一个请求的servlet
     */
    class RequestServlet extends HttpServlet {

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            log.info("client connect");
            ServletInputStream inputStream = req.getInputStream();
            ServletOutputStream outputStream = resp.getOutputStream();

            if (handler != null) {
                handler.onRequest(inputStream, outputStream);
            }
            outputStream.flush();
        }
    }
}
